import React, { useState, useEffect } from 'react';
import { Teacher, stageOptions } from '../../../shared/models';
import { useData } from '../../../shared/DataContext';
import './AddEditTeacherModal.css';
interface AddEditTeacherModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (teacher: Teacher) => void;
  teacher: Teacher | null;
  isEditing: boolean;
}

const AddEditTeacherModal: React.FC<AddEditTeacherModalProps> = ({
  isOpen,
  onClose,
  onSave,
  teacher,
  isEditing
}) => {
  // 选项数据定义
  const subjectOptions = [
    { value: 'chinese', label: '语文' },
    { value: 'math', label: '数学' },
    { value: 'english', label: '英语' },
    { value: 'physics', label: '物理' },
    { value: 'chemistry', label: '化学' },
    { value: 'biology', label: '生物' },
    { value: 'history', label: '历史' },
    { value: 'geography', label: '地理' },
    { value: 'politics', label: '政治' }
  ];

  // 使用从shared/models.ts导入的stageOptions，添加全部阶段选项
  const enhancedStageOptions = [
    { value: 'all', label: '全部阶段' },
    ...stageOptions
  ];

  // 从数据上下文获取academyOptions
  const { academyOptions } = useData();

  const positionOptions = [
    { value: 'teacher', label: '教师' },
    { value: 'headteacher', label: '班主任' },
    { value: 'director', label: '教导主任' },
    { value: 'principal', label: '校长' }
  ];

  const educationOptions = [
    { value: 'bachelor', label: '本科' },
    { value: 'master', label: '硕士' },
    { value: 'doctor', label: '博士' },
    { value: 'associate', label: '大专' }
  ];

  const statusOptions = [
    { value: 'active', label: '在职' },
    { value: 'leave', label: '请假' },
    { value: 'resigned', label: '已离职' },
    { value: 'retired', label: '已退休' }
  ];

  const departmentOptions = [
    { value: 'chinese', label: '语文组' },
    { value: 'math', label: '数学组' },
    { value: 'english', label: '英语组' },
    { value: 'science', label: '科学组' },
    { value: 'humanities', label: '人文组' },
    { value: 'administration', label: '行政部门' }
  ];

  // 表单状态
  const [formData, setFormData] = useState<Teacher>({
    id: '',
    name: '',
    gender: 'male',
    subject: 'chinese',
    stage: 'freshman',
    academy: '人工智能',
    position: 'teacher',
    education: 'bachelor',
    dateOfBirth: '',
    hireDate: '',
    phone: '',
    email: '',
    address: '',
    status: 'active',
    department: 'chinese',
    qualifications: []
  });

  const [newQualification, setNewQualification] = useState('');
  const [errors, setErrors] = useState<Record<string, string>>({});

  // 当编辑模式或教师数据变化时，更新表单数据
  useEffect(() => {
    if (isEditing && teacher) {
      setFormData({
        ...teacher,
        qualifications: teacher.qualifications || []
      });
    } else if (!isEditing) {
      // 重置为默认值
      setFormData({
        id: '',
        name: '',
        gender: 'male',
        subject: 'chinese',
        stage: 'freshman',
        academy: '人工智能',
        position: 'teacher',
        education: 'bachelor',
        dateOfBirth: '',
        hireDate: '',
        phone: '',
        email: '',
        address: '',
        status: 'active',
        department: 'chinese',
        qualifications: []
      });
    }
    setErrors({});
    setNewQualification('');
  }, [isEditing, teacher]);

  // 处理表单字段变化
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
    // 清除该字段的错误
    if (errors[name]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  // 添加资格证书
  const handleAddQualification = () => {
    if (newQualification.trim()) {
      setFormData(prev => ({
        ...prev,
        qualifications: [...prev.qualifications!, newQualification.trim()]
      }));
      setNewQualification('');
    }
  };

  // 删除资格证书
  const handleRemoveQualification = (index: number) => {
    setFormData(prev => ({
      ...prev,
      qualifications: prev.qualifications!.filter((_, i) => i !== index)
    }));
  };

  // 验证表单
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    // 必填字段验证
    if (!formData.name.trim()) newErrors.name = '请输入教师姓名';
    if (!formData.dateOfBirth) newErrors.dateOfBirth = '请选择出生日期';
    if (!formData.hireDate) newErrors.hireDate = '请选择入职日期';
    if (!formData.phone.trim()) {
      newErrors.phone = '请输入联系电话';
    } else if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      newErrors.phone = '请输入有效的手机号码';
    }
    if (!formData.email.trim()) {
      newErrors.email = '请输入电子邮箱';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = '请输入有效的电子邮箱地址';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理表单提交
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (validateForm()) {
      onSave(formData);
      onClose();
    }
  };

  // 处理模态框关闭
  const handleClose = () => {
    if (Object.values(formData).some(value => 
      value !== null && value !== undefined && value.toString().trim() !== ''
    )) {
      if (window.confirm('表单内容尚未保存，确定要关闭吗？')) {
        onClose();
      }
    } else {
      onClose();
    }
  };

  if (!isOpen) return null;

  return (
    <div className="modal-overlay">
      <div className="modal-container">
        <div className="modal-header">
          <h2>{isEditing ? '编辑教师' : '添加教师'}</h2>
          <button className="modal-close" onClick={handleClose}>&times;</button>
        </div>
        
        <div className="modal-body">
          <form onSubmit={handleSubmit}>
            <div className="form-section">
              <h3>基本信息</h3>
              <div className="form-row">
                <div className="form-group">
                  <label htmlFor="name">姓名 *</label>
                  <input
                    type="text"
                    id="name"
                    name="name"
                    value={formData.name}
                    onChange={handleChange}
                    className={errors.name ? 'error' : ''}
                  />
                  {errors.name && <span className="error-message">{errors.name}</span>}
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label htmlFor="gender">性别</label>
                  <select
                    id="gender"
                    name="gender"
                    value={formData.gender}
                    onChange={handleChange}
                  >
                    <option value="male">男</option>
                    <option value="female">女</option>
                  </select>
                </div>
                
                <div className="form-group">
                  <label htmlFor="dateOfBirth">出生日期 *</label>
                  <input
                    type="date"
                    id="dateOfBirth"
                    name="dateOfBirth"
                    value={formData.dateOfBirth}
                    onChange={handleChange}
                    className={errors.dateOfBirth ? 'error' : ''}
                  />
                  {errors.dateOfBirth && <span className="error-message">{errors.dateOfBirth}</span>}
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label htmlFor="position">职位</label>
                  <select
                    id="position"
                    name="position"
                    value={formData.position}
                    onChange={handleChange}
                  >
                    {positionOptions.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
                
                <div className="form-group">
                  <label htmlFor="education">学历</label>
                  <select
                    id="education"
                    name="education"
                    value={formData.education}
                    onChange={handleChange}
                  >
                    {educationOptions.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
            </div>

            <div className="form-section">
              <h3>工作信息</h3>
              <div className="form-row">
                <div className="form-group">
                  <label htmlFor="subject">科目</label>
                  <select
                    id="subject"
                    name="subject"
                    value={formData.subject}
                    onChange={handleChange}
                  >
                    {subjectOptions.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
                
                <div className="form-group">
                  <label htmlFor="stage">教授阶段</label>
                  <select
                    id="stage"
                    name="stage"
                    value={formData.stage}
                    onChange={handleChange}
                  >
                    {enhancedStageOptions.filter(opt => opt.value !== 'all').map(option => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
                  </select>
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label htmlFor="academy">学院</label>
                  <select
                    id="academy"
                    name="academy"
                    value={formData.academy}
                    onChange={handleChange}
                  >
                    {academyOptions.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
                
                <div className="form-group">
                  <label htmlFor="department">部门</label>
                  <select
                    id="department"
                    name="department"
                    value={formData.department}
                    onChange={handleChange}
                  >
                    {departmentOptions.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
                
                <div className="form-group">
                  <label htmlFor="hireDate">入职日期 *</label>
                  <input
                    type="date"
                    id="hireDate"
                    name="hireDate"
                    value={formData.hireDate}
                    onChange={handleChange}
                    className={errors.hireDate ? 'error' : ''}
                  />
                  {errors.hireDate && <span className="error-message">{errors.hireDate}</span>}
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label htmlFor="status">状态</label>
                  <select
                    id="status"
                    name="status"
                    value={formData.status}
                    onChange={handleChange}
                  >
                    {statusOptions.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
                
                <div className="form-group">
                  <label htmlFor="salaryLevel">薪资等级 (可选)</label>
                  <input
                    type="text"
                    id="salaryLevel"
                    name="salaryLevel"
                    value={formData.salaryLevel || ''}
                    onChange={handleChange}
                    placeholder="如：level1, level2"
                  />
                </div>
              </div>
            </div>

            <div className="form-section">
              <h3>联系方式</h3>
              <div className="form-row">
                <div className="form-group">
                  <label htmlFor="phone">联系电话 *</label>
                  <input
                    type="tel"
                    id="phone"
                    name="phone"
                    value={formData.phone}
                    onChange={handleChange}
                    className={errors.phone ? 'error' : ''}
                  />
                  {errors.phone && <span className="error-message">{errors.phone}</span>}
                </div>
                
                <div className="form-group">
                  <label htmlFor="email">电子邮箱 *</label>
                  <input
                    type="email"
                    id="email"
                    name="email"
                    value={formData.email}
                    onChange={handleChange}
                    className={errors.email ? 'error' : ''}
                  />
                  {errors.email && <span className="error-message">{errors.email}</span>}
                </div>
              </div>

              <div className="form-group">
                <label htmlFor="address">家庭住址 (可选)</label>
                <textarea
                  id="address"
                  name="address"
                  value={formData.address}
                  onChange={handleChange}
                  rows={3}
                  placeholder="请输入家庭住址"
                />
              </div>
            </div>

            <div className="form-section">
              <h3>资格证书 (可选)</h3>
              <div className="qualifications-container">
                <div className="qualification-input-group">
                  <input
                    type="text"
                    value={newQualification}
                    onChange={(e) => setNewQualification(e.target.value)}
                    placeholder="输入证书名称"
                    className="qualification-input"
                  />
                  <button
                    type="button"
                    onClick={handleAddQualification}
                    className="btn-add-qualification"
                  >
                    添加
                  </button>
                </div>
                
                {formData.qualifications && formData.qualifications.length > 0 && (
                  <div className="qualifications-list">
                    {formData.qualifications.map((qualification, index) => (
                      <div key={index} className="qualification-item">
                        <span>{qualification}</span>
                        <button
                          type="button"
                          onClick={() => handleRemoveQualification(index)}
                          className="btn-remove-qualification"
                        >
                          删除
                        </button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>

            <div className="modal-footer">
              <button type="button" onClick={handleClose} className="btn-cancel">
                取消
              </button>
              <button type="submit" className="btn-save">
                保存
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default AddEditTeacherModal;